/* 
 * Bitmain Tech, Home of Professional Bitmain Tech
 * Copyright 2014 Bitmain Tech Inc. and/or its affiliates and other contributors
 * as indicated by the @author tags. All rights reserved.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 */
package com.bitmain.mmst.feature.mybatis.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.util.PGobject;

import com.bitmain.ulnar.aider.JSONAider;
import com.google.gson.reflect.TypeToken;

/**
 * JSON类型字段转换
 *
 * @author Kweny - enkun.jiang@bitmain.com
 * @since 2015年12月21日
 *
 */
public class JsonTypeHandler<T> extends BaseTypeHandler<T> {

	/* (non-Javadoc)
	 * @see org.apache.ibatis.type.BaseTypeHandler#setNonNullParameter(java.sql.PreparedStatement, int, java.lang.Object, org.apache.ibatis.type.JdbcType)
	 */
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType)
			throws SQLException {
		PGobject jsonObject = new PGobject();
		jsonObject.setType("json");
		jsonObject.setValue(JSONAider.toJson(parameter));
		ps.setObject(i, jsonObject);
	}

	/* (non-Javadoc)
	 * @see org.apache.ibatis.type.BaseTypeHandler#getNullableResult(java.sql.ResultSet, java.lang.String)
	 */
	@Override
	public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return JSONAider.fromJson(rs.getString(columnName), new TypeToken<T>() {});
	}

	/* (non-Javadoc)
	 * @see org.apache.ibatis.type.BaseTypeHandler#getNullableResult(java.sql.ResultSet, int)
	 */
	@Override
	public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return JSONAider.fromJson(rs.getString(columnIndex), new TypeToken<T>() {});
	}

	/* (non-Javadoc)
	 * @see org.apache.ibatis.type.BaseTypeHandler#getNullableResult(java.sql.CallableStatement, int)
	 */
	@Override
	public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return JSONAider.fromJson(cs.getString(columnIndex), new TypeToken<T>() {});
	}

}
